package com.yeung.web;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 从application域中得到ioc容器
        ServletContext servletContext = getServletContext();
        ApplicationContext context = (ApplicationContext) servletContext.getAttribute("ApplicationContext");
        if (context == null)
            context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        //2. 从ioc容器中获取bean
        //使用spring的contextLoaderListener的话会扫描整个项目的配置文件
        Person person = context.getBean(Person.class);
        if (person == null) person = new Person("from spring contextLoaderListener");
        //3. 执行相关业务逻辑
        person.hello();

    }
}
